<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Cck\ArticlesSystem\Services\SettingsService;

if (!function_exists('put_file')) {
    function put_file(UploadedFile $file, string $pathPrefix = null): string
    {
        $pathPrefix = $pathPrefix ?: date('Y/m/d');

        return Storage::disk()->putFile($pathPrefix, $file);
    }
}

if (!function_exists('get_file_url_by_path')) {
    function get_file_url_by_path(string $path): string
    {
        return Storage::disk()->url($path);
    }
}

if (!function_exists('settings')) {
    function settings(string $name, $default = null)
    {
        return app(SettingsService::class)->getSettingValue($name, $default);
    }
}

/**
 * 随机数字和字符串
 *
 * @param integer $minLength
 * @param integer $maxLength
 * @return void
 */
function randomNumbersAndLetters(int $minLength = 2, int $maxLength = null)
{
    $maxLength = max(2, $maxLength);
    $minLength = max(2, $minLength);
    $maxLength = max($minLength, $maxLength);
    $minLength = min($minLength, $maxLength);
    $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $stringCount = strlen($string);

    $length = mt_rand($minLength, $maxLength);

    $result = '';

    for ($i = 0; $i < $length; $i++) {
        $result .= $string[mt_rand(0, $stringCount - 1)];
    }

    return $result;
}

/**
 * 随机数字
 *
 * @param integer $minLength
 * @param integer $maxLength
 * @return void
 */
function randomNumbers(int $minLength = 1, int $maxLength = null)
{
    $minLength = min($minLength, $maxLength);
    $maxLength = max($minLength, $maxLength);

    return mt_rand(
        str_pad($minLength, $minLength, '0', STR_PAD_RIGHT),
        str_pad($maxLength, $maxLength, '0', STR_PAD_RIGHT)
    );
}

/**
 * 随机字母
 *
 * @param integer $min
 * @param integer $max
 * @return void
 */
function randomLetters(int $min = 1, int $max = null)
{
    $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $lettersCount = strlen($letters);

    $min = min($min, $max);
    $max = max($min, $max);

    $length = mt_rand($min, $max);

    $result = '';

    for ($i = 0; $i < $length; $i++) {
        $result .= $letters[mt_rand(0, $lettersCount - 1)];
    }

    return $result;
}
